﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;
using QbservableCore.Serialization.Helpers;
using System.Runtime.Serialization;

namespace QbservableCore.Serialization
{
    [DataContract]
    public class NewInstanceNode : ExpRepresentationBase
    {
        [DataMember]
        public ExpRepresentationBase[] Arguments { get; set; }

        [DataMember]
        public SerializableMethodBase ConstructorToken;

        protected internal override Expression ToExpression(ExepressionBuilderCache exepressionBuilderCache)
        {
            Expression[] args = new Expression[Arguments.Length];
            for (int index = 0; index < args.Length; index++)
            {
                args[index] = Arguments[index].ToExpression(exepressionBuilderCache);
            }
            // ConstructorInfo constructor = (ConstructorInfo)ConstructorToken.Deserialize();
            ConstructorInfo constructor = (ConstructorInfo)ConstructorToken.Method;
            return Expression.New(constructor, args);
        }

        protected override void TraverseChildren(Func<ExpRepresentationBase, ExpRepresentationBase> action)
        {
            TraverseNodes(Arguments, action);
        }

        public override string ToString()
        {
            string args = string.Join(", ", Arguments.Cast<object>());
            return string.Format("new {0}()", args);
        }
    }
}